package com.sskj.cndragon.ui.activity;


import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.Group;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.bulong.rudeness.RudenessScreenHelper;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.permissions.RxPermissions;
import com.shizhefei.mvc.MVCCoolHelper;
import com.shizhefei.view.coolrefreshview.CoolRefreshView;
import com.sskj.cndragon.R;
import com.sskj.cndragon.bean.RecordListBean;
import com.sskj.cndragon.bean.ShaiTuListBean;
import com.sskj.cndragon.http.HttpConfig;
import com.sskj.cndragon.presenter.GetQuanActivityPresenter;
import com.sskj.cndragon.view.SelectPictureDialog;
import com.sskj.cndragon.view.ToolBarLayout;
import com.sskj.common.adapter.slimadapter.IViewInjector;
import com.sskj.common.adapter.slimadapter.SlimAdapter;
import com.sskj.common.adapter.slimadapter.SlimInjector;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.TimeFormatUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.BaseHttpConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.mvchelper.ModelRx2DataSource;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Flowable;
import io.reactivex.internal.util.VolatileSizeArrayList;


public class GetQuanActivity extends BaseActivity<GetQuanActivityPresenter> {
    @BindView(R.id.toolbar)
    ToolBarLayout toolbar;
    @BindView(R.id.view0)
    View view0;
    @BindView(R.id.group)
    Group group;
    @BindView(R.id.iv_upload)
    ImageView ivUpload;
    @BindView(R.id.btn_shenhe)
    Button btnShenhe;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.coolRefreshView)
    CoolRefreshView coolRefreshView;

    private SlimAdapter<ShaiTuListBean.ShaiTuBean> slimAdapter;
    private MVCCoolHelper<List<ShaiTuListBean.ShaiTuBean>> mvcHelper;

    private String imageUrl;
    private SelectPictureDialog selectPictureDialog;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_get_quan;
    }

    @Override
    public GetQuanActivityPresenter getPresenter() {
        return new GetQuanActivityPresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        toolbar.setLeftButtonOnClickListener(view -> finish());
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerLineItemDecoration(this)
                .setPaintWidth((int) RudenessScreenHelper.pt2px(this, 10))
                .setPaintColor(ContextCompat.getColor(this, R.color.transparent))
                .setFirstDraw(false)
                .setLastDraw(false));

        slimAdapter = SlimAdapter.create().register(R.layout.item_tijiao, new SlimInjector<ShaiTuListBean.ShaiTuBean>() {
            @Override
            public void onInject(ShaiTuListBean.ShaiTuBean data, IViewInjector injector, List payloads) {
                //0 待审核 1 审核通过 2 审核失败
                injector.text(R.id.tv_status, data.getInspectStatus() == 0 ? App.INSTANCE.getString(R.string.appDaishenhe) :
                        data.getInspectStatus() == 1 ? App.INSTANCE.getString(R.string.appShenhetongguo) :
                                data.getInspectStatus() == 2 ? App.INSTANCE.getString(R.string.appShenheshibai) : "")
                        .textColor(R.id.tv_status, data.getInspectStatus() == 2 ?
                                ContextCompat.getColor(App.INSTANCE, R.color.color_ff1) :
                                ContextCompat.getColor(App.INSTANCE, R.color.white))
                        .visibility(R.id.group, data.getInspectStatus() == 2 ? View.VISIBLE : View.GONE)
                        .text(R.id.tv1, data.getInspectStatus() == 0 ?
                                "" : App.INSTANCE.getString(R.string.shenheshijian))
                        .text(R.id.tv_date_upload, TimeFormatUtil.formatB(data.getCreateTime()))
                        .text(R.id.tv_time_upload, TimeFormatUtil.formatH(data.getCreateTime()))
                        .text(R.id.tv_date_check, isEmpty(data.getInspectTime()) ? "" : TimeFormatUtil.formatB(Long.valueOf(data.getInspectTime())))
                        .text(R.id.tv_time_check, isEmpty(data.getInspectTime()) ? "" : TimeFormatUtil.formatH(Long.valueOf(data.getInspectTime())))
                        .text(R.id.tv_msg, data.getInspectReason())
                        .image(R.id.iv_picture, data.getImgUrl().contains("http") ?
                                data.getImgUrl() : BaseHttpConfig.BASE_URL + data.getImgUrl());
            }
        }).attachTo(recyclerView).updateData(new ArrayList());
        mvcHelper = new MVCCoolHelper<>(coolRefreshView);
        ModelRx2DataSource<ShaiTuListBean.ShaiTuBean> dataSource = new ModelRx2DataSource<>(
                (ModelRx2DataSource.OnLoadSource<ShaiTuListBean.ShaiTuBean>)
                        page -> mPresenter.getShaiTuRecord(page), 10);
        mvcHelper.setAdapter(slimAdapter);
        mvcHelper.setDataSource(dataSource);
        mvcHelper.setAutoLoadMore(true);
        mvcHelper.setNeedCheckNetwork(false);
        mvcHelper.refresh();

        ClickUtil.click(300, view0, () -> {
            new RxPermissions(GetQuanActivity.this)
                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                    .subscribe(granted -> {
                        if (granted) {
                            selectPic();
                        }
                    });
        });
        ClickUtil.click(300, ivUpload, () -> {
            new RxPermissions(GetQuanActivity.this)
                    .request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                    .subscribe(granted -> {
                        if (granted) {
                            selectPic();
                        }
                    });
        });
        ClickUtil.click(300, btnShenhe, new ClickUtil.Click() {
            @Override
            public void click() {
                if (isEmpty(imageUrl)) {
                    ToastUtil.showShort(App.INSTANCE.getString(R.string.appQingxianshangchuanshaitujietu));
                    return;
                }
                mPresenter.shaiTu(SPUtil.get(SPConfig.ID, ""), imageUrl);
            }
        });

    }

    public void selectPic() {
        if (selectPictureDialog == null) {
            selectPictureDialog = new SelectPictureDialog(this);
        }
        selectPictureDialog.setOnSelectListener(new SelectPictureDialog.SelectListener() {
            @Override
            public void selectByAlbum() {
                PictureSelector.create(GetQuanActivity.this)
                        .openGallery(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .compress(true)
                        .minimumCompressSize(100)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }

            @Override
            public void selectByPhoto() {
                PictureSelector.create(GetQuanActivity.this)
                        .openCamera(PictureMimeType.ofImage())
                        .maxSelectNum(1)
                        .compress(true)
                        .minimumCompressSize(100)
                        .forResult(PictureConfig.CHOOSE_REQUEST);
            }
        });
        selectPictureDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 图片、视频、音频选择结果回调
        if (resultCode == RESULT_OK && requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
            String mImagePath = TextUtils.isEmpty(selectList.get(0).getCompressPath()) ? selectList.get(0).getPath() : selectList.get(0).getCompressPath();
            mPresenter.uploadFile(new File(mImagePath));
        }
    }

    public void changeHead(String headUrl) {
        if (headUrl == null) {
            return;
        }
        imageUrl = headUrl;
        ivUpload.setVisibility(View.VISIBLE);
        ImageUtil.setImage(HttpConfig.BASE_URL + headUrl, ivUpload);
        group.setVisibility(View.INVISIBLE);
    }

    public static void start(Context context) {
        Intent intent = new Intent(context, GetQuanActivity.class);
        context.startActivity(intent);
    }

    public void shaituOK() {
        imageUrl = "";
        ivUpload.setVisibility(View.GONE);
        group.setVisibility(View.VISIBLE);
        if (mvcHelper != null) {
            mvcHelper.refresh();
        }
    }

    public void shaituFail() {
        imageUrl = "";
    }
}
